<template>
  <div class="main">
    <!-- 左侧菜单 -->
    <div class="sidebar">
      <div class="logo">
        <img src="@/assets/Logo.png" alt="Logo" />
      </div>
      <ul class="menu">
        <li>
          <router-link to="/personalcenter">个人中心</router-link>
        </li>
        <li>
          <router-link to="/viewrecording">浏览记录</router-link>
        </li>
        <li class="parent-menu" :class="{ active: isSubmenuOpen }" @click="toggleSubmenu">
          <a href="#" class="parent-link">账户设置
            <span class="toggle-icon">^</span>
          </a>
          <ul class="submenu">
            <li><router-link to="/personalinfo">个人资料</router-link></li>
            <li><router-link to="/preference-settings">偏好设置</router-link></li>
          </ul>
        </li>
      </ul>
    </div>

    <!-- 右侧内容 -->
    <div class="content">
      <div class="content-header">
        <div style="display: flex; align-items: center;">
          <img :src="avatarUrl" alt="用户头像" class="avatar" />
          <span class="username">{{ displayName }}</span>
        </div>
        <!-- 返回主页按钮 -->
        <router-link to="/home" class="home-button">返回主页</router-link>
      </div>

      <div class="feature-cards">
        <router-link to="/shopping-cart" class="feature-card">我的购物车></router-link>
        <router-link to="/viewrecording" class="feature-card">浏览记录></router-link>
      </div>

      <h2 class="section-title">猜你喜欢</h2>
      <div class="recommendations">
        <div v-if="loading" class="recommend-loading">正在加载推荐商品...</div>
        <div v-else-if="error" class="recommend-error">{{ error }}</div>
        <div v-else-if="recommendedProducts.length === 0" class="recommend-empty">暂无推荐数据</div>
        <template v-else>
          <div v-for="item in recommendedProducts" :key="item.productId" class="product-card">
            <div class="product-image">
              <img :src="item.imageUrl || defaultAvatar" :alt="item.productName || '商品图片'" />
            </div>
            <div class="product-name">{{ item.productName || '商品' }}</div>
            <div class="product-review">
              <span class="user">{{ item.platformName || '平台' }}:</span>
              推荐价 {{ formatPrice(item.price) }}
            </div>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getCurrentUser, getRecommendProducts } from '@/api'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

const isSubmenuOpen = ref(false)
const recommendedProducts = ref([])
const loading = ref(false)
const error = ref('')

const defaultAvatar = new URL('@/assets/Logo.png', import.meta.url).href
const avatarUrl = computed(() => userStore.info?.icon || defaultAvatar)
const displayName = computed(() => userStore.userName || '用户')

const toggleSubmenu = () => {
  isSubmenuOpen.value = !isSubmenuOpen.value
}

const ensureUserInfo = async () => {
  if (!userStore.isLoggedIn) {
    router.push('/user-login')
    return false
  }
  if (!userStore.info) {
    try {
      const res = await getCurrentUser()
      if (res?.data) {
        userStore.setUserInfo(res.data)
      }
    } catch (error) {
      console.warn('获取用户信息失败，即将返回登录页', error)
      userStore.clearAuth()
      router.push('/user-login')
      return false
    }
  }
  return true
}

const normalizeRecommendList = (payload) => {
  if (!payload) return []
  if (Array.isArray(payload)) return payload
  if (Array.isArray(payload.data)) return payload.data
  return []
}

const formatPrice = (value) => {
  const num = Number(value)
  if (Number.isFinite(num)) {
    return `¥${num.toFixed(2)}`
  }
  if (value !== null && value !== undefined && value !== '') {
    return `¥${value}`
  }
  return '¥0.00'
}

const loadRecommendProducts = async () => {
  loading.value = true
  error.value = ''
  try {
    const response = await getRecommendProducts(9)
    recommendedProducts.value = normalizeRecommendList(response)
  } catch (err) {
    console.error('加载推荐商品失败:', err)
    error.value = '加载推荐商品失败，请稍后重试'
    recommendedProducts.value = []
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  const ok = await ensureUserInfo()
  if (ok) {
    await loadRecommendProducts()
  }
})
</script>

<style scoped>
@import '@/CSS/UserPublicCss.css';

/* 右侧内容区域：唯一可滚动的部分 */
@import '@/CSS/PersonalCenter.css';
</style>
